<template>
  <div :class="['el-col', classList]" :style="style">
    <slot></slot>
  </div>
</template>

<script setup>
import { ref, defineProps, computed, inject, getCurrentInstance } from "vue";

//获取当前组件实例
const vm = getCurrentInstance();

const {
  proxy: { $parent },
} = vm;

const props = defineProps({
  span: {
    type: Number,
    default: 24, //默认24等份
  },
  offset: {
    type: Number,
    default: 0,
  },
  push: {
    type: Number,
    default: 0,
  },
  pull: {
    type: Number,
    default: 0,
  },
});
//先用span动态计算占据父级的百分之多少,再用gutter计算列布局左右padding值举例
//获取el-row父组件的gutter的值,从而动态的设置el-col的paddgin值
const gutter = computed(() => {
  //找到父级,可能父级不是el-row,存在嵌套问题,直到直到el-row为止
  let parent = $parent;
  //$options 原型上可以到name名称
  while (parent && parent.$options["name"] !== "ElRow") {
    //递归往上查找
    parent = parent.$parent;
  }
  return parent ? parent.gutter : 0;
});

//设置col等份的左右padding值
const style = computed(() => {
  const style = {};
  if (gutter && gutter.value) {
    style.paddingLfet = gutter.value / 2 + "px";
    style.paddingRight = gutter.value / 2 + "px";
  }
  return style;
});

//整合class类名数组
const classList = computed(() => {
  const classList = [];
  const classItem = ["span", "offset", "push", "pull"];
  //vue3不要使用this 啊！！！！！！！！！！！！！
  classItem.forEach((item) => {
    if (props[item]) {
      classList.push(item === "span" ? `el-col-${props[item]}` : `el-col-${item}-${props[item]}`);
    }
  });
  return classList;
});
</script>

<style lang="scss" scoped>
.el-col {
  float: left;
  box-sizing: border-box;
}

@for $i from 0 through 24 {
  .el-col-#{$i} {
    width: $i / 24 * 100%;
  }
  .el-col-offset-#{$i} {
    margin-left: $i / 24 * 100%;
  }
  .el-col-push-#{$i} {
    position: relative;
    left: $i / 24 * 100%;
  }
  .el-col-pull-#{$i} {
    position: relative;
    right: $i / 24 * 100%;
  }
}
</style>
